﻿using AForge.Video.DirectShow;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using WPFMediaKit.DirectShow.Controls;
using ZXing;
using ZXing.Common;
using ZXing.QrCode.Internal;

namespace CardMonitor.Windows
{
    /// <summary>
    /// QRCameraWindow.xaml 的交互逻辑
    /// </summary>
    public partial class QRCameraWindow : Window
    {
        BarcodeReader codeReader = new BarcodeReader();

        /// <summary>
        /// 定时器
        /// </summary>
        DispatcherTimer cameraTimer = new DispatcherTimer();
        public QRCameraWindow()
        {
            InitializeComponent();
            //FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            //if (videoDevices.Count > 0)
            //{
            //    var videoDevice = new VideoCaptureDevice(videoDevices[0].MonikerString);
            //    videoDevice.VideoResolution = videoDevice.VideoCapabilities[0];  //设置分辨率
            //    player.VideoSource = videoDevice; //设置源
            //    player.Start(); //启动
            //    cameraTimer.IsEnabled = false;
            //    cameraTimer.Interval = new TimeSpan(200); //执行间隔0.2秒
            //    cameraTimer.Tick += cameraTimer_Tick;
            //}
            //this.Loaded += Window_Loaded;
            var camera = "Integrated Camera";
            if (MultimediaUtil.VideoInputNames.Contains(camera))
            {
                //控件制定摄像头
                vce.VideoCaptureSource = camera;
                cameraTimer.IsEnabled = false;
                cameraTimer.Interval = new TimeSpan(1000); //执行间隔0.2秒
                //cameraTimer.Tick += cameraTimer_Tick;
                cameraTimer.Tick += new EventHandler(cameraTimer_Tick);

            }


        }

        private void BtnShiBie_Click(object sender, RoutedEventArgs e)
        {
            cameraTimer.Start();
        }
        //private void Window_Loaded(object sender, RoutedEventArgs e)
        //{
        //    //现在电脑上装的所有摄像头中，选择一个摄像头。
        //    cb.ItemsSource = MultimediaUtil.VideoInputNames;
        //    //设置第0个摄像头为默认摄像头。
        //    if (MultimediaUtil.VideoInputNames.Length > 0)
        //    {
        //        cb.SelectedIndex = 0;
        //    }
        //    else
        //    {
        //        MessageBox.Show("电脑没有安装任何摄像头");
        //    }
        //}
        private void cameraTimer_Tick(object sender, EventArgs e)
        {
            RenderTargetBitmap bmp = new RenderTargetBitmap((int)vce.ActualWidth, (int)vce.ActualHeight, 96, 96, PixelFormats.Default);
            vce.Measure(vce.RenderSize);
            vce.Arrange(new Rect(vce.RenderSize));
            bmp.Render(vce);
            BitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bmp));
            using (MemoryStream ms = new MemoryStream())
            {
                encoder.Save(ms);
                Bitmap btiMap = new Bitmap(ms);
                var result = codeReader.Decode(btiMap);//解析条码
                if (result != null)
                {
                    // 1:停止识别
                    cameraTimer.Stop();
                    vce.Play();
                    MessageBox.Show($"识别内容为：{result}");

                }
            }
        }

        private void BtnShnegCeng_Click(object sender, RoutedEventArgs e)
        {
            var codimg = Create("车牌号：鲁E12345 运输介质：柴油 运输量：33吨");
            imgQR.Source = ChangeBitmapToImageSource(codimg);
        }
        /// <summary>
        /// 创建二维码
        /// </summary>
        /// <param name="msg">二维码中保存的信息</param>
        /// <returns></returns>
        public static Bitmap Create(string msg)
        {
            MultiFormatWriter writer = new MultiFormatWriter();
            Dictionary<EncodeHintType, object> hint = new Dictionary<EncodeHintType, object>();
            //设置二维码为utf-8编码
            hint.Add(EncodeHintType.CHARACTER_SET, "utf-8");
            //设置纠错等级， 高
            hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            BitMatrix bm = writer.encode(msg, BarcodeFormat.QR_CODE, 200, 120, hint);
            BarcodeWriter barcodeWriter = new BarcodeWriter();
            Bitmap bitmap = barcodeWriter.Write(bm);
            string codePath = Directory.GetCurrentDirectory() + "/code.jpg";
            if (File.Exists(codePath))
                File.Delete(codePath);
            bitmap.Save(codePath);
            return bitmap;
        }
        public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
        {
            IntPtr hBitmap = bitmap.GetHbitmap();

            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());

            //if (!DeleteObject(hBitmap))
            //{
            //    throw new System.ComponentModel.Win32Exception();
            //}
            return wpfBitmap;
        }
    }
}
